package com.vin.controller;

import com.vin.pojo.User;
import com.vin.pojo.Result;
import com.vin.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.vin.utils.MD5Utils;
@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public Result register( @Pattern(regexp = "^\\S{5,16}$")  String username,  @Pattern(regexp = "^\\S{5,16}$")  String password){
      User u =   userService.findByUserName(username);
      if(u == null){
            userService.register(username,password);
            return Result.success();
      }else{
            return Result.error("用户名已经被占用");
      }
    }
    @PostMapping("/login")
    public Result login( @Pattern(regexp = "^\\S{5,16}$")  String username,  @Pattern(regexp = "^\\S{5,16}$")  String password){
        //根据用户名判断用户是否存在
        User loginUser = userService.findByUserName(username);
        if(loginUser == null){
            return Result.success("用户不存在");
        }
        //如果存在则根据用户名判断密码是否正确
        if(MD5Utils.getMD5String(password).equals(loginUser.getPassword())){
            return Result.success("jwt 令牌...");
        }
        return Result.error("密码错误");
    }
}
